package com.pine.dcts.task;

import com.pine.dcts.common.TaskStatusType;
import com.pine.dcts.service.TaskRunnerCallback;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Future;

/**
 *  任务执行结果处理类
 * @author xiaoyuan
 * @create 2021/6/2 10:54
 **/
@Slf4j
public class TaskExecutorCallback implements Runnable {

    private Future future;
    private TaskRunnerCallback callback;

    private  TaskStatCollector taskStatCollector;

    public TaskExecutorCallback(Future future, TaskRunnerCallback callback,  TaskStatCollector taskStatCollector) {
        this.future = future;
        this.callback = callback;
        this.taskStatCollector = taskStatCollector;
    }

    @Override
    public void run() {
        try {
            future.get();
            callback(callback, TaskStatusType.FINISH, "任务完成");
        } catch (Exception e) {
            if (future.isCancelled()) {
                future.cancel(true);
            }
            log.error("任务执行出现错误，原因：{}，任务强行中断", e.getMessage(), e);
            callback(callback, TaskStatusType.ERROR, String.format("任务出现异常：%s", e.getMessage()));
        } finally {
            taskStatCollector.remove(callback.getTaskMeta().getTaskId());
        }
    }


    private void callback(TaskRunnerCallback callback, TaskStatusType statusType, String message) {
        callback.setTaskStatus(statusType);
        callback.setMessage(message);
        callback.callback();
    }
}
